// login.js
// import {getWxLogin, getUserProfile} from '../../utils/util';
let fn = require('../../utils/Requestutil'); 
Page({
  data: {
    baseUrl: "",
    checked: true
  },
  // 勾选协议
  onChange: function (event) {
    this.setData({
      checked: event.detail // 更新复选框状态
    });
    // 校验是否勾选了复选框
    if (!this.data.checked) {
      // 如果未勾选，则提示用户
      wx.showToast({
        title: '请勾选同意协议',
        icon: 'none',
        duration: 2000
      });
    }
  },
  async login(){
    const token = wx.getStorageSync('token');
    if(!token){
      Promise.all([fn.getWxLogin(),fn.getUserProfile()]).then((res) =>{
        // console.log(res[0].code);
        // console.log(res[1].userInfo.avatarUrl,res[1].userInfo.nickName)
        let loginParam = {
          code: res[0].code,
          nickName: res[1].userInfo.nickName,
          avatarUrl: res[1].userInfo.avatarUrl
        }
        console.log(loginParam);
        wx.setStorageSync('userInfo', res[1].userInfo);
        this.wxlogin(loginParam);
      }).then(() => {
        // 在用户授权后返回上一页
        wx.navigateBack();
      }).catch((err) => {
        console.log("授权失败", err);
      });
    }else{
      console.log("token存在：" + token);
    }
    
  },
/**
 * 请求后端获取用户token
 * @param {*} loginParam 
 */
  async wxlogin(loginParam){
    const result = await fn.requestUtil({url:"/user/wxlogin",data:loginParam,method:"post"});
    console.log(result.student)
    const {token, userId , student} = result;
    if(result.code === 0){
      // 存储token
      wx.setStorageSync('token', token);
      wx.setStorageSync('userId', userId);
      wx.setStorageSync('student', student)
      console.log("已存储的token、userId、student：",token, userId, student);
    }
  }
})